package com.app.wechart.ChartManager;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.app.wechart.R;

import java.util.ArrayList;

public class MessageListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    public ArrayList<MessageInfo> arrayList;

    public MessageListAdapter(Context c,ArrayList<MessageInfo> list){
        this.context = c;
        this.arrayList = list;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(this.context).inflate(viewType == 2?R.layout.other_message:R.layout.own_message,parent,false);
        return new ItemHolder(v,viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ItemHolder v = (ItemHolder) holder;
        MessageInfo messageInfo = this.arrayList.get(position);
        if(!messageInfo.fromType.equals("1")){
            v.ll_title.setText(messageInfo.userName);
        }
        v.ll_desc.setText(messageInfo.msg);
        if (messageInfo.msg.length()>2){
            v.ll_desc.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        }
    }

    @Override
    public int getItemViewType(int position) {
        MessageInfo messageInfo =  this.arrayList.get(position);
        if (messageInfo.fromType.equals("1")){
            return  1;
        }
        return 2;
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }



    public class ItemHolder extends RecyclerView.ViewHolder{
        public LinearLayout ll_item;
        public TextView ll_title;
        public TextView ll_desc;
        public ImageView ll_pic;
        public ItemHolder(@NonNull View itemView,int viewType) {
            super(itemView);
            if (viewType == 2){
                ll_item = itemView.findViewById(R.id.other_item);
                ll_title = itemView.findViewById(R.id.other_title);
                ll_desc = itemView.findViewById(R.id.other_msg);
                ll_pic = itemView.findViewById(R.id.other_pic);
            }else {
                ll_item = itemView.findViewById(R.id.own_item);
                ll_desc = itemView.findViewById(R.id.own_msg);
                ll_pic = itemView.findViewById(R.id.own_pic);
            }
        }
    }

    public void addMessage(MessageInfo messageInfo){
        this.arrayList.add(messageInfo);
        this.notifyItemChanged(this.arrayList.size()-1);
    }


}
